package cn.gbase.jiangsu.data.transfer.action;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.log4j.Logger;
import org.nutz.dao.Chain;
import org.nutz.dao.Cnd;
import org.nutz.dao.Dao;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.service.Service;

import cn.gbase.jiangsu.data.transfer.bean.DataEvent;
import cn.gbase.jiangsu.data.transfer.bean.ShopUsersCoupon;
import cn.gbase.jiangsu.data.transfer.dto.EventParam;
import cn.gbase.jiangsu.data.transfer.util.CommonUtil;

/**
 * 事件触发的处理（如用户注册送优惠券，事件就是“用户注册”，动作就是“送优惠券”.
 */
@IocBean(args = { "refer:dao" })
public class EventAction extends Service {

	private static final Logger logger = Logger.getLogger(EventAction.class);

	/**
	 * 动作Map.
	 */
	private Map<String, String> actionMap = new HashMap<String, String>();

	public EventAction(Dao dao) {
		super(dao);
		init();
	}

	/**
	 * 初始化.
	 */
	private void init() {
		actionMap.put("单个用户送优惠券", "^满(\\d+)减(\\d+),(\\d+)张,有效期(\\d+)天$");
	}

	/**
	 * 触发事件.
	 * 
	 * @param param
	 */
	public void triggerEvent(EventParam param) {
		if (param == null) {
			return;
		}

		// 事件名称
		String eventName = param.getEventName();
		if (param.getEventName() == null || param.getEventName().length() == 0) {
			return;
		}

		// 取得事件的动作列表，已启用的
		List<DataEvent> eventList = this.dao().query(DataEvent.class, Cnd.where("eventName", "=", eventName).and("isEnable", "=", 1));
		if (eventList.size() == 0) {
			return;
		}

		// 处理每个事件
		for (DataEvent event : eventList) {
			try {
				doOneAction(param, event);
			} catch (Exception e) {
				logger.error("事件处理出错。", e);
			}
		}
	}

	/**
	 * 处理单个事件.
	 * 
	 * @param param
	 *            事件参数
	 * @param actionStr
	 *            动作字符串
	 */
	private void doOneAction(EventParam param, DataEvent event) {

		// 判断Key是否存在
		String actionKey = event.getActionKey();
		if (!actionMap.containsKey(actionKey)) {
			throw new RuntimeException("id为" + event.getId() + "的事件，" + actionKey + "没有对应的处理程序.");
		}

		// 正则
		String regex = actionMap.get(actionKey);

		// 多的话，写工厂类，这里先凑合着
		if (actionKey.equals("单个用户送优惠券")) {

			// 取出每个参数值
			Matcher m = Pattern.compile(regex, Pattern.CASE_INSENSITIVE).matcher(event.getActionStr());
			if (!m.matches()) {
				throw new RuntimeException("id为" + event.getId() + "的事件，" + actionKey + "，动作字符串无法匹配。");
			}

			// 满50减5,2张,有效期30天
			int needMoney = Integer.valueOf(m.group(1));
			int faceValue = Integer.valueOf(m.group(2));
			int count = Integer.valueOf(m.group(3));
			int days = Integer.valueOf(m.group(4));

			// 有效日期
			Date validDateFrom = CommonUtil.getToday000000(); // 今天0点开始
			Date validDateTo = CommonUtil.getTodayAddDay000000(days); // 30天后的0点结束

			// 循环
			for (int i = 0; i < count; i++) {

				// 插入优惠券
				ShopUsersCoupon row = new ShopUsersCoupon();
				row.setCouponNo(""); // 先空着
				row.setDeleteFlag(0);
				row.setFaceValue(faceValue);
				row.setIsUsed(0);
				row.setNeedMoney(needMoney);
				row.setUserId(param.getUserId());
				row.setValidDateFrom(validDateFrom);
				row.setValidDateTo(validDateTo);
				this.dao().insert(row);

				// 更新优惠券编号
				String no = formateCouponNo(row.getId());
				this.dao().update(ShopUsersCoupon.class, Chain.make("couponNo", no), Cnd.where("id", "=", row.getId()));
			}
		}

	}

	/**
	 * 格式化优惠券编号.
	 * 
	 * @param id
	 * @return
	 */
	private String formateCouponNo(int id) {

		// 如id为12345，则格式化为：1000012345
		return "1" + CommonUtil.fixLengthNumber(id, 9);
	}
}